package qeug.shsh.opplugin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.param.AppCustomParam;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.parameter.SystemParamServiceHelper;
import okhttp3.*;
import qeug.shsh.helper.FacadeHelper;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

public class ExtractVoucherOp extends AbstractOperationServicePlugIn {
    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        List<AbstractValidator> validators = e.getValidators();
        // 删除标品校验器

//        validators.removeIf(validator -> validator instanceof PaymentMaxAmountValidator);
//        validators.removeIf(validator -> validator instanceof PaymentTypeValidator);
        // 添加定制二开的校验器（位置放第一位，优先执行）
        validators.add(0, new ExtractVoucherValidator());
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        try {
            QFilter[] q1 = new QFilter[]{new QFilter("qeug_issap", "=", true)};
            DynamicObject[] bosOrgs = BusinessDataServiceHelper.load("bos_org", "qeug_issap,id,number", q1);
            List<String> orgNum =new ArrayList();
            for (DynamicObject bosOrg : bosOrgs) {
                orgNum.add(bosOrg.getString("number"));
            }

            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 获取当前年并转换为字符串
            String currentYear = String.valueOf(currentDate.getYear());
            // 获取当前月并转换为字符串，若为个位数则不显示前面的 0
            int monthValue = currentDate.getMonthValue();
            String currentMonth = String.valueOf(monthValue);
            String url=  System.getProperty("sapacc.url");
            url = "http://10.10.101.131:50000/RESTAdapter/CCS2S4/getACC";
            String basicAuthUserName = "ccsuser";
            HashMap<String, Object> log = new HashMap<>();
            log.put("operationModule", "手动抽取凭证");
            log.put("url", url);
            log.put("user", basicAuthUserName);
            log.put("mode", "POST");
            log.put("action", "");
            log.put("opdate", new Date());
            //根据应用编码从缓存中获取应用信息
            AppInfo cgfwAppInfo = AppMetadataCache.getAppInfo("gl");
            //获取应用的主键
            String appId = cgfwAppInfo.getId();
            AppCustomParam appCustomParam = new AppCustomParam(appId);
            Map<String, String> cusTomMap = SystemParamServiceHelper.loadAppCustomParameterFromCache(appCustomParam);
//            for (int i = 0; i < orgNum.size(); i++) {
//                for (int j = 0; j < cusTomMap.size(); j++) {
//                    String kjkm = cusTomMap.get(j);
            JSONObject body = new JSONObject();
//                    body.put("BUKRS", orgNum.get(i));
//            body.put("GJAHR", currentYear);
//            body.put("MONAT", currentMonth);
//            body.put("RACCT", kjkm);
            body.put("BUKRS", "5800");
            body.put("GJAHR", "2024");
            body.put("MONAT", "2");
//                    body.put("RACCT", kjkm);
            String sapapi = FacadeHelper.getSAPAPI(body.toJSONString(), url);
            JSONArray voucher = FacadeHelper.getVoucher(sapapi);
            if (voucher==null){
//                        continue;
            }
            String result = createVoucherStructure(voucher);
            log.put("mainstring", body.toJSONString());
            log.put("responsebody", sapapi);
            JSONObject date = JSONObject.parseObject(result).getJSONObject("date");
            int failCount = Integer.parseInt(date.getString("failCount"));
            if (failCount > 0) {
                log.put("pdesc", "失败");
                log.put("operating_mode", date.getJSONArray("result"));
                FacadeHelper.apiLog(log);
            } else {
                log.put("pdesc", "成功");
                FacadeHelper.apiLog(log);
            }
//                }
//            }
        } catch (ParseException e1) {
            throw new RuntimeException(e1);
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    }


    public static String createVoucherStructure(JSONArray jsonArray) throws ParseException, IOException {
//        String voucher = sapService.getVoucher(body.toJSONString());;
        JSONObject root = new JSONObject(new LinkedHashMap<>());
        JSONArray dataArray = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            boolean isAccountview = true;
            JSONObject sapInfo = jsonArray.getJSONObject(i);
            String BUKRS = sapInfo.getString("BUKRS");//公司代码
            DynamicObject company = FacadeHelper.getDynamicObject("bos_org", "number", BUKRS);
            String GJAHR = sapInfo.getString("GJAHR");//年度
//            String GJAHR = "2024";//年度
            String MONAT = sapInfo.getString("MONAT");//期间
            DynamicObject period = FacadeHelper.getDynamicObject("bd_period", "number", GJAHR + MONAT);
            String BELNR = sapInfo.getString("BELNR");//凭证编号
            String BLDAT = sapInfo.getString("BLDAT");//业务日期
            String bizDate = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(BLDAT));
            String BUDAT = sapInfo.getString("BUDAT");//记账日期
            String jzDate = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(BUDAT));
            SimpleDateFormat sf = new SimpleDateFormat();
            sf.applyPattern("yyyy-mm-dd");
//            Date bizDate = sf.parse(BLDAT);
//            Date jzDate = sf.parse(BUDAT);
            String BLART = sapInfo.getString("BLART");//凭证类型
//                        DynamicObject vouchertype = FacadeHelper.getDynamicObject("gl_vouchertype", "number", BLART);
            DynamicObject vouchertype = FacadeHelper.getDynamicObject("gl_vouchertype", "number", "0001");
//            String BELNR = sapInfo.getString("BELNR");//凭证号
            String SNAME = sapInfo.getString("SNAME");//制单人

//                        DynamicObject user = FacadeHelper.getDynamicObject("bos_user", "number", SNAME);
            DynamicObject user = FacadeHelper.getDynamicObject("bos_user", "number", "18115209696");
            String KURSF = sapInfo.getString("KURSF");//汇率
            String WAERS = sapInfo.getString("WAERS");//币别代码
            DynamicObject currency = FacadeHelper.getDynamicObject("bd_currency", "number", "CNY");
            String BKTXT = sapInfo.getString("BKTXT");//凭证抬头文本
            String STJAH = sapInfo.getString("STJAH");//冲销年度
            String STBLG = sapInfo.getString("STBLG");//冲销由（冲销凭证号）
            String XBLNR = sapInfo.getString("XBLNR");//参考信息
            String AWKEY = sapInfo.getString("AWKEY");//对象键值

            // 构建 DataItem
            JSONObject dataItem = new JSONObject(true);
            dataItem.put("org_number", BUKRS);
            dataItem.put("booktype_number", "100001");
            dataItem.put("period_number", period.getString("number"));
            dataItem.put("billno", BELNR);
            dataItem.put("billstatus", "A");
            dataItem.put("vouchertype_number", "0001");
            dataItem.put("vdescription", BKTXT);
            dataItem.put("bizdate", bizDate);
            dataItem.put("bookeddate", jzDate);
            dataItem.put("description", XBLNR);
            dataItem.put("attachment", 0);
            dataItem.put("creator_number", "SAP");
            dataItem.put("createtime", new Date());
            JSONArray voucherItem = sapInfo.getJSONArray("items");
            JSONArray entriesArray = new JSONArray();
            for (int j = 0; j < voucherItem.size(); j++) {
                JSONObject voucherentry = voucherItem.getJSONObject(j);
                //明细
                String DOCLN = voucherentry.getString("DOCLN").trim();//凭证行项目编号
                String SGTXT = voucherentry.getString("SGTXT");//凭证行项目文本
                String RACCT = voucherentry.getString("RACCT");//科目代码
                DynamicObject accountview = FacadeHelper.getDynamicObject("bd_accountview", "qeug_sapnumber", RACCT);
                if (accountview != null) {
                    RACCT = accountview.getString("number");
                } else {
//                    isAccountview = false;
//                    continue;
                    RACCT  = "1002010101";
                }
//                DynamicObject accountview = FacadeHelper.getDynamicObject("bd_accountview", "number", "1221.02");
                String MATNR = voucherentry.getString("MATNR");//物料号
                String WSL = voucherentry.getString("WSL").trim();//以交易货币计的金额
                String DRCRK = voucherentry.getString("DRCRK");//借/贷标识
                String RCNTR = voucherentry.getString("RCNTR");//成本中心代码
                DynamicObject bos_costcenter = FacadeHelper.getDynamicObject("bos_costcenter", "number", RCNTR);
                String AUFNR = voucherentry.getString("AUFNR");//内部订单号
                String ZZFZHS02 = voucherentry.getString("ZZFZHS02");//辅助核算02
                String ZZFZHS03 = voucherentry.getString("ZZFZHS03");//辅助核算03
                // 构建 Entries

                JSONObject entry = new JSONObject(true);
                entry.put("seq", Integer.valueOf(DOCLN));

                if (DRCRK.equals("S")) {//jie
                    entry.put("debitori", new BigDecimal(FacadeHelper.formatNumber(WSL)));
                    entry.put("debitlocal", new BigDecimal(FacadeHelper.formatNumber(WSL)));
                    entry.put("creditori", BigDecimal.ZERO);
                    entry.put("creditlocal", BigDecimal.ZERO);
                } else if (DRCRK.equals("H")) {//dai
                    entry.put("creditori", new BigDecimal(FacadeHelper.formatNumber(WSL)));
                    entry.put("creditlocal", new BigDecimal(FacadeHelper.formatNumber(WSL)));
                    entry.put("debitori", BigDecimal.ZERO);
                    entry.put("debitlocal", BigDecimal.ZERO);
                }
                entry.put("localrate", BigDecimal.ONE);
//                entry.put("price", BigDecimal.ZERO);
                entry.put("edescription", SGTXT);
//                entry.put("quantity", BigDecimal.ZERO);
//                entry.put("maincfamount", BigDecimal.ZERO);
//                entry.put("suppcfamount", BigDecimal.ZERO);
                entry.put("currency_number", "CNY");
                entry.put("account_number", RACCT);

                // 构建 assgrp
                JSONObject assGrp = new JSONObject(true);
//                assGrp.put("id", "700017576538920960");
                assGrp.put("订单编号", AUFNR);
                JSONObject baseMaterial2 = new JSONObject(true);
//                baseMaterial2.put("id", "8923874751601479680");
//                baseMaterial2.put("name", "k7hZv");
                baseMaterial2.put("number", RCNTR);
                assGrp.put("成本中心", baseMaterial2);
//                assGrp.put("弹性域名称-辅助资料类型", baseMaterial2.clone());
                entry.put("assgrp", assGrp);
                entriesArray.add(entry);
                DynamicObject expInfo = new DynamicObject();
            }
            dataItem.put("entries", entriesArray);
            dataItem.put("qeug_objectkey", AWKEY);
            dataItem.put("qeug_cxvoucher", STBLG);
            dataItem.put("qeug_sys", "SAP");
            if (isAccountview) {
                dataArray.add(dataItem);
            }
        }

        root.put("data", dataArray);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, root.toJSONString());
        Request request = new Request.Builder()
                .url("http://10.10.102.30:30088/ierp/kapi/v2/qeug/gl/gl_voucher/newsavevoucher")//uat
                .method("POST", body)
                .addHeader("access_token", FacadeHelper.getToken())
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        String string = response.body().string();
        System.out.println(string);
        return string;
    }
}
